import React from "react";
import { Form, Input, Select, Button, DatePicker } from 'antd';

const { Option } = Select;
const { RangePicker } = DatePicker;

const refs = {};

// 转元素组件
const returnElement = (props, setValue) => {

    const ref = React.createRef();

    switch (props.type) {
        case 'Input': {
            return <Input type="text" placeholder={props.placeholder} allowClear />
        }
        case 'Select': {
            const { options, onChange } = props;
            const options_items = options.map((item, index) => {
                return <Option key={index} value={item.value}>{item.text}</Option>
            });
            if(onChange){
                return <Select placeholder={props.placeholder} onChange={onChange} showSearch>{options_items}</Select>
            }
            return <Select placeholder={props.placeholder} showSearch allowClear>{options_items}</Select>
        }
        case 'DatePicker': {
            return <DatePicker placeholder={props.placeholder} />
        }
        case 'RangePicker': {
            refs[props.name] = ref;
            return <RangePicker ref={ref} range={props.range} placeholder={props.placeholder} />
        }
        case 'Component': {
            return <props.component name={props.name} setValue={setValue} />
        }
        default: return null
    }
};

// 搜索
const Search = (props) => {

    const { config: {columns, rightOpt}, search } = props;
    const [form] = Form.useForm();

    const onReset = () => {
        form.resetFields();
        search({})
    };
    const onFinish = (values) => {
        const t_values = {};
        for(let key in values){
            if(Array.isArray(values[key])){
                const { range, value } = refs[key].current.props;
                t_values[range[0]] = value[0].format('YYYY-MM-DD');
                t_values[range[1]] = value[1].format('YYYY-MM-DD');
            }else {
                if(values[key]){
                    t_values[key] = values[key]
                }
            }
        }
        search(t_values)
    };
    return (
        <div className="search-box">
            <Form layout="inline" form={form} onFinish={onFinish}>
                {
                    columns.map((item, index) => {
                        return (
                            <Form.Item key={index} name={item.name}>
                                {returnElement(item, form.setFieldsValue)}
                            </Form.Item>
                        )
                    })
                }
                <Form.Item>
                    <Button type="primary" htmlType="submit">查询</Button>
                    <Button htmlType="button" onClick={onReset}>重置</Button>
                </Form.Item>
            </Form>
            {rightOpt && rightOpt()}
        </div>
    )
};

export default Search